package com.swc.sign;

import com.swc.constant.HeaderConstant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author HU
 * @date 2020/12/18 10:10
 */

public class Sha256Sign {

	private Logger logger = LoggerFactory.getLogger(Sha256Sign.class);

    private static final String GA = "ga";

    private HttpServletRequest request;

    public Sha256Sign() {}

    public Sha256Sign(HttpServletRequest request) {
        this.request = request;
    }

    public void dealRequestHeader(Map<String, String> data) {
    	if(StringUtils.isNotEmpty(request.getHeader(HeaderConstant.HEADER_ENCRYPT_MODE))) {
			data.put(HeaderConstant.HEADER_ENCRYPT_MODE, request.getHeader(HeaderConstant.HEADER_ENCRYPT_MODE));
		}
		if(StringUtils.isNotEmpty(request.getHeader(HeaderConstant.HEADER_RESP_ENCRYPT))) {
			data.put(HeaderConstant.HEADER_RESP_ENCRYPT, request.getHeader(HeaderConstant.HEADER_RESP_ENCRYPT));
		}
		if(StringUtils.isNotEmpty(request.getHeader(HeaderConstant.HEADER_SECRET_KEY))) {
			data.put(HeaderConstant.HEADER_SECRET_KEY, request.getHeader(HeaderConstant.HEADER_SECRET_KEY));
		}
		if(StringUtils.isNotEmpty(request.getHeader(HeaderConstant.HEADER_TOKEN_KEY))) {
			data.put(HeaderConstant.HEADER_TOKEN_KEY, request.getHeader(HeaderConstant.HEADER_TOKEN_KEY));
		}

        // ga开头的都要验签
        /*Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            if (headerName.startsWith(GA)) {
                String header = request.getHeader(headerName);
                if (StringUtils.isNotEmpty(header)) {
                    data.put(headerName, header);
                }
            }
        }*/
    }

    public String verifySign(Map<String, String> treeMap, String secretKey) {
        try {
        	StringBuilder data = new StringBuilder();
			Iterator<String> it = treeMap.keySet().iterator();
			while (it.hasNext()) {
				String key = it.next();
				if(it.hasNext()) {
					data.append(key).append("=").append(treeMap.get(key)).append("&");
				} else {
					data.append(key).append("=").append(treeMap.get(key));
				}
			}
			logger.info("sign data:{}", data);
			Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec sha256SecretKey = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
			sha256Hmac.init(sha256SecretKey);
            byte[] array = sha256Hmac.doFinal(data.toString().getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
            }
            return sb.toString();
        } catch (Exception e) {
			logger.error("签名处理异常", e);
            throw new RuntimeException("签名处理异常");
        }
    }

	public static void main(String[] args) {
		Map<String, String> map = new TreeMap<>();
		map.put(HeaderConstant.HEADER_ENCRYPT_MODE, "3");
		map.put(HeaderConstant.HEADER_RESP_ENCRYPT, "1");
		map.put(HeaderConstant.HEADER_SECRET_KEY, "DoEUpCphRv6h2BVZCVEDrndOm8awzytWHqhLbsbzhBKUGdiQfyVwrk3Evmk+l3wM4y5J3t7bkmCdqKh/Bj97c+A35vlRUC35MKDSOyPMr3tYfyKJlQQIUJV+Ros1ZQlCHiDjmWYD73+WdktpLVnAUlEyYDVQI9kihID9z5crvM4=");
		map.put("request", "Jfv66kO3Uqg6NwYfJuc6sA==");

		Sha256Sign sha256Sign = new Sha256Sign();
		System.out.println("----------------------------------------");
		System.out.println(sha256Sign.verifySign(map, "QWQ18@QSW134RfC!"));
	}
}
